//
//  ViewController.swift
//  ContainerView
//
//  Created by hengchengfei on 16/2/26.
//  Copyright © 2016年 fundsmart. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var currentController:UIViewController!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        currentController = self.childViewControllers[0] as! AViewController
 
    }

    @IBAction func A(){
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("AViewController")  as! AViewController
 
        replaceViewController(currentController, new: vc)
    }
    
    @IBAction func B(){
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("BViewController") as! BViewController

        replaceViewController(currentController, new: vc)
    }
    
    
    func replaceViewController(old:UIViewController,new:UIViewController){
        old.willMoveToParentViewController(nil)
        self.addChildViewController(new)
        new.view.frame = old.view.frame
        
        currentController = new
        // 此处的动画duration一定要设置为0,因为如果非常快的来回切换,则会造成前一个VC已经删除,再执行切换时,造成crash
        self.transitionFromViewController(old, toViewController: new, duration: 0.8, options: UIViewAnimationOptions.TransitionFlipFromLeft, animations: nil) { (finished) -> Void in
            if finished {
                old.removeFromParentViewController()
                new.didMoveToParentViewController(self)
            }
        }
    }
}

